# django_app/db_utils.py
import os
import sys
import time

import django
from django.db import transaction, DatabaseError
from django.db.models import F
from django_redis import get_redis_connection
current_dir = os.path.dirname(os.path.abspath(__file__))         # 当前文件目录
project_root = os.path.dirname(os.path.dirname(current_dir))     # 上两级目录

# 添加项目根目录到 Python 路径
sys.path.insert(0, project_root)
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'seckill_java_topy.settings')
# 初始化 Django 环境
django.setup()
from orders.models import Order, SeckillOrder
from goods.models import SeckillGoods, Goods


class DjangoORMHelper:
    @staticmethod
    def deduct_stock(goods_id: int, max_retries=3) -> bool:
        """同步库存扣减（带重试）"""
        for attempt in range(max_retries):
            try:
                with transaction.atomic():
                    seckill_goods = SeckillGoods.objects.select_for_update().get(goods_id=goods_id)

                    if seckill_goods.stock_count <= 0:
                        return False

                    # 扣减秒杀库存
                    SeckillGoods.objects.filter(
                        id=seckill_goods.id,
                        stock_count=seckill_goods.stock_count
                    ).update(stock_count=F('stock_count') - 1)

                    # 扣减普通库存
                    Goods.objects.filter(id=goods_id).update(
                        goods_stock=F('goods_stock') - 1
                    )
                    return True

            except DatabaseError as e:
                if attempt == max_retries - 1:
                    raise
                time.sleep(0.1)

        return False

    @staticmethod
    def create_order(goods_id: int, user_id: int) -> dict:
        """同步订单创建"""
        try:
            with transaction.atomic():
                goods = Goods.objects.get(id=goods_id)
                seckill_goods = SeckillGoods.objects.get(goods_id=goods_id)

                order = Order.objects.create(
                    user_id=user_id,
                    goods_id=goods_id,
                    goods_name=goods.goods_name,
                    goods_count=1,
                    goods_price=seckill_goods.seckill_price,
                    status=0
                )

                SeckillOrder.objects.create(
                    user_id=user_id,
                    goods_id=goods_id,
                    order=order
                )
                return order
        except Exception as e:
            raise